<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>waibibabo</title>
</head>

<body>
    <div id="app">
        <div>
            <textarea rows="10" id="waibi" onchange="tran()"></textarea>
            <textarea rows="10" id="biwai"></textarea>
            <input type="button" value="翻译" onclick=tran() />
            <input type="button" value="复制" onclick=copy() />
        </div>
    </div>
    <script type="text/javascript">
        function waibi(input) {
            let str = input
            let len = str.length
            let res = ''
            const charWaibi = (c) => {
                const dic = ["歪", "比", "吧"]
                let l = c.length
                let r = ""
                for (let i = 0; i < l; i++) {
                    r += dic[c[i]]
                }
                return r
            }
            for (let i = 0; i < len; i++) {
                let tmp = str[i].charCodeAt(0).toString(3)
                res += charWaibi(tmp) + "卜"
            }
            return res
        };
        function biwai(input) {
            const charWaibi = (c) => {
                const dic = { "歪": "0", "比": "1", "吧": "2" }
                let l = c.length
                let r = ""
                for (let i = 0; i < l; i++) {
                    r += dic[c[i]] || ""
                }
                return r
            }
            let arr = input.split("卜")
            arr.pop()
            let res = arr.reduce((a, c) => {
                if (c) {
                    let code = parseInt(charWaibi(c) || 0, 3)
                    return a + String.fromCharCode(code)
                } else {
                    return a
                }
            }, '')
            return res
        };
        function tran() {
            let input = document.getElementById("waibi").value;
            let reg = /(歪|比|巴|卜)+/
            if (reg.test(input) && input != "歪比巴卜" && input != "歪比巴" && input != "歪比" && input != "歪") {
                document.getElementById("biwai").value = biwai(input);
            } else {
                document.getElementById("biwai").value = waibi(input);
            }
        }
        function copy() {
            var biwai = document.getElementById("biwai").value;
            let transfer = document.createElement('input');
            document.body.appendChild(transfer);
            transfer.value = biwai;
            transfer.focus();
            transfer.select();
            if (document.execCommand('copy')) {
                document.execCommand('copy');
            }
            transfer.blur();
            document.body.removeChild(transfer);
        }
    </script>


</body>

</html>